package gotlib

import (
	"bytes"
	"os"
	"os/exec"
	"time"
)

// OSCreateDir basePath是固定目录路径
func OSCreateDir(basePath string, folderName string) (newFolderPath string) {
	if !OSIsDir(basePath) {
		return ""
	}
	newFolderPath = PathLink(basePath, folderName)
	if OSIsDir(newFolderPath) {
		return newFolderPath
	}
	// 必须分成两步// 先创建文件夹
	err := os.Mkdir(newFolderPath, 0777)
	if err != nil {
		return ""
	}
	// 再修改权限
	err = os.Chmod(newFolderPath, 0777)
	if err != nil {
		return ""
	}
	return newFolderPath
}

// OSIsDir 判断所给路径是否为文件夹
func OSIsDir(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		return false
	}
	return s.IsDir()
}

// OSIsFile 判断所给路径是否为文件
func OSIsFile(path string) bool {
	if OSPathExists(path) {
		return !OSIsDir(path)
	} else {
		return false
	}
}

// OSPathExists 判断文件、文件夹是否存在
func OSPathExists(path string) bool {
	_, err := os.Stat(path) //os.Stat获取文件信息
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}

// PathIsExist 检查文件或路径是否存在
func PathIsExist(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

// OSGetCurrentDir 得到当前目录
func OSGetCurrentDir() (path string) {
	path, _ = os.Getwd()
	return
}

// OSExecCommand 执行Dos或Shell命令
func OSExecCommand(cmdString string, params ...string) (outStr string, errStr string, err error) {
	cmd := exec.Command(cmdString, params...)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout // 标准输出
	cmd.Stderr = &stderr // 标准错误
	err = cmd.Run()
	outStr, errStr = string(stdout.Bytes()), string(stderr.Bytes())
	return
}

func FileNameAddDateTime(fileName string) string {
	sFlag := "."
	sTime := time.Now().Format("20060102150405")
	if StrIndex(fileName, sFlag) < 0 {
		return StrJoin("", fileName, sTime)
	}
	return StrJoin("", StrLeftBack(fileName, sFlag), sTime, sFlag, StrRightBack(fileName, sFlag))
}

func PathLink(path1, path2 string) string {
	link := path1[len(path1)-1:]
	if link == "\\" || link == "/" {
		return StrJoin("", path1, path2)
	} else {
		return StrJoin("", path1, "/", path2)
	}
}
